package com.dd.stack.se.stream.concurrent.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/28 15:16
 * @Description 类功能作用说明
 */
public class FairLockExample {
    // 创建公平锁（默认是非公平锁）
    private final ReentrantLock fairLock = new ReentrantLock(true);

    public void accessResource() {
        for (int i = 0; i < 2; i++) { // 每个线程尝试获取2次锁
            fairLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " 获取锁");
            } finally {
                fairLock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        FairLockExample example = new FairLockExample();
        // 启动3个线程，公平锁会按请求顺序分配锁
        for (int i = 0; i < 5; i++) {
            new Thread(example::accessResource, "线程" + i).start();
        }
    }
}
